package com.mingweicai.intergration.controller;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

  private Logger logger = LoggerFactory.getLogger(TestController.class);

  @RequestMapping(value = "/metrics", method = RequestMethod.GET)
  public void metrics(HttpServletResponse response) throws IOException {
    response.getWriter().print(((PrometheusMeterRegistry) meterRegistry).scrape());
  }

  @Autowired
  @Qualifier("meter")
  private MeterRegistry meterRegistry;

  @RequestMapping("/test")
  public void test(HttpServletRequest request, HttpServletResponse response) throws InterruptedException {
    response.setContentType("application/problem+json");
    ResponseEntity<String> responseEntity = new ResponseEntity<String>("{}", HttpStatus.SERVICE_UNAVAILABLE);
    sendHttpResponse(response, responseEntity);
  }


  public void sendHttpResponse(HttpServletResponse httpServletResponse, ResponseEntity<String> responseEntity) {
    try {
      HttpStatus status = responseEntity.getStatusCode();
      httpServletResponse.setContentType("application/problem+json");
      if (status.value() != 503){
        logger.info("Before: response status is not 503");
      }
      httpServletResponse.setStatus(status.value());

      addCustomHeaders(responseEntity, httpServletResponse);
      httpServletResponse.setCharacterEncoding(StandardCharsets.UTF_8.name());
      if (responseEntity.getBody() != null && status != HttpStatus.NO_CONTENT) {
        writeHttpResponse(httpServletResponse, (String)responseEntity.getBody());
        return;
      }
    } catch (IOException var7) {
      logger.error("Send http response to As failed with IOException", var7);
      throw new RuntimeException("Send http response to As failed with IOException");
    } finally {
    }

  }


  private static void addCustomHeaders(ResponseEntity<String> responseEntity, HttpServletResponse httpServletResponse) {
    HttpHeaders headers = responseEntity.getHeaders();
    Set<String> headerKeys = headers.keySet();
    if (headerKeys != null && headerKeys.size() != 0) {
      Iterator var4 = headerKeys.iterator();

      while (true) {
        String key;
        List headerValues;
        do {
          do {
            if (!var4.hasNext()) {
              return;
            }

            key = (String)var4.next();
            headerValues = headers.get(key);
          } while(headerValues == null);
        } while(headerValues.size() == 0);

        Iterator var7 = headerValues.iterator();

        while (var7.hasNext()) {
          String value = (String)var7.next();
          httpServletResponse.addHeader(key, value);
        }
      }
    }
  }

  private void writeHttpResponse(HttpServletResponse response, String httpBody) throws IOException {
    PrintWriter writer = null;

    try {
      writer = response.getWriter();
      writer.write(httpBody);
    } finally {
      if (writer != null) {
        writer.flush();
      }

    }

  }
}
